import type { IQuery, Response, TableResponse } from '@/api/config/types';
import { exportFile } from '@/api/utils/file';
import axios from 'axios';
import type { SystemMenu } from '../../system/menu/types';

export enum GenWebType {
  MOBILE = 'MOBILE', // 仅移动端
  MOBILE_JAVA = 'MOBILE_JAVA', // 移动端+java
  PC_JAVA = 'PC_JAVA', // PC端+java
  JAVA = 'JAVA', // 仅后端
  PC = 'PC', // 仅PC端
  SQL = 'SQL', // 仅SQL
  API = 'API', // 仅前端API接口
}

export const fetchCodeList = (query: IQuery) => {
  return axios.get<TableResponse<SystemTable>>(`tool/gen/list`, { params: query });
};

export const fetchCodeById = (id: number) => {
  return axios.get<Response<CodeResponse>>(`tool/gen/${id}`);
};

export const createCode = (data: any) => {
  return axios.post<Response>(`tool/gen`, data);
};

export const updateCode = (data: any) => {
  return axios.put<Response>(`tool/gen`, data);
};

export const deleteCodeByIds = (ids: string) => {
  return axios.delete<Response>(`tool/gen/${ids}`);
};
// 同步代码
export const synchDb = (db: string) => {
  return axios.get(`tool/gen/synchDb/${db}`);
};

export const fetchGenDbList = (query: IQuery) => {
  return axios.get(`tool/gen/db/list`, {
    params: query,
  });
};
/**
 * @description:
 * @param {number} code 表ID
 * @param {GenWebType} type
 */
export const previewCode = (code: number, type: GenWebType) => {
  return axios.get<Response<GenCode>>(`tool/gen/preview/${code}`, {
    params: {
      type,
    },
  });
};

/* 导入表的数据 */
export const importDbByDbs = (dbs: string[]) => {
  return axios.post(`tool/gen/importTable?tables=${dbs.join(',')}`);
};

/* 下载代码 */
export const batchGenCode = (tables: string[], type: GenWebType) => {
  return exportFile({
    url: `tool/gen/batchGenCode?tables=${tables.join(',')}`,
    params: {
      type,
    },
    fileName: `ax_${tables.join(',')}.zip`,
    method: 'GET',
  });
};
/**
 * @description: 生成单页面
 * @param {*} type 页面类型
 * @param {string} path 绝对路径=文件路径+文件名
 */

type PageConfig = {
  filePath: string;
  /* 生成页面的类型 */
  type: 'single';
  fileCreated: '0' | '1';
} & Partial<SystemMenu>;
export const generateSinglePage = (config: PageConfig) => {
  return axios.post(`tool/gen/generateSinglePage`, config);
};

type GenCodeFile = {
  /* 表名 */
  tableName: string;
  /* 前端路径 */
  frontendPath: string;
  /* 后端路径 */
  backendPath: string;
  /* 生成的类型 */
  type: GenWebType;
  /* 是否立即执行SQL */
  runSql: boolean;
  /* 强制覆盖 */
  forceOverride: boolean;
};
/* 直接把代码写入文件中 */
export const genCodeFile = (config: GenCodeFile) => {
  return axios.post(`tool/gen/genCodeFile`, {
    ...config,
  });
};
